<template>
  <div
    class="scroll-container"
    :style="`overflow-y:${isRoll?'auto':'hidden'}`"
    ref="scroll-container"
  >
    <div class="scroll-box" ref="scroll-box" @mouseover="_onOver" @mouseleave="_onLeave">
      <div :style="`transform:translateY(-${translateY}px)`" ref="scroll-box-item">
        <slot />
      </div>
      <div :style="`transform:translateY(-${translateY}px)`" v-html="listHtml"></div>
    </div>
  </div>
</template>
<script>
export default {
  name: "data-v-scroll",
  props: {
    step: {
      //步长 控制快慢
      type: Number,
      default: 2
    },
    isRoll: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      reqFrame: null,
      translateY: 0,
      listHtml: "",
      scroll_box_height: 0,
      itemHeight: 0
    };
  },
  methods: {
    runScroll() {
      //清除可能有鼠标hover 引起多次动画冲突；
      this._stopScroll();
      /*
       * 如何子元素集合高度小于容器高度 则直接返回
       */
      if (this.itemHeight < this.scroll_box_height) return;
      //开始动画
      this.reqFrame = requestAnimationFrame(() => {
        this.translateY += this.step;
        this.runScroll();
        if (this.translateY >= this.itemHeight) {
          this.translateY = 0;
        }
      });
    },
    //鼠标离开
    _onLeave() {
      let scrollTop = this.$refs["scroll-container"].scrollTop;
      let { translateY, scroll_box_height } = this;
      if (scrollTop + translateY >= scroll_box_height) {
        this.$refs["scroll-container"].scrollTop = 0;
      }

      this.runScroll();
    },
    //鼠标移入
    _onOver() {
      this._stopScroll();
    },
    //动画停止
    _stopScroll() {
      cancelAnimationFrame(this.reqFrame || "");
    },

    //赋值比较
    compare() {
      let scroll_box_height = this.$refs["scroll-box"].clientHeight; //容器高度
      let itemHeight = this.$refs["scroll-box-item"].scrollHeight; //子元素集合的高度
      if (scroll_box_height < itemHeight) {
        this.listHtml = this.$refs["scroll-box-item"].innerHTML;
        this.runScroll();
      }
      this.scroll_box_height = scroll_box_height;
      this.itemHeight = itemHeight;
    }
  },
  mounted() {
    this.compare();
  }
};
</script>
<style lang="less" src='./index.less' scoped></style>